#include "stdafx.h"
#include "wf_blocksremove.h"

#include "pf_insert.h"


WF_BlocksRemove::WF_BlocksRemove(PF_Container& container,
        PF_GraphicView& graphicView)
        :PF_ActionInterface("Remove Block", container, graphicView) {}


QAction* WF_BlocksRemove::createGUIAction(LX_Define::ActionType /*type*/, QObject* /*parent*/) {
	// tr("Remove Block")
	QAction* action = new QAction(tr("&Remove Block"), NULL);
    //action->zetStatusTip(tr("Remove Block"));
	action->setIcon(QIcon(":/ui/blockremove.png"));
	return action;
}

void WF_BlocksRemove::trigger() {
    PF_DEBUG->print("PF_ActionBlocksRemove::trigger");

    if (graphic!=NULL) {
        PF_Block* block =
            PF_DIALOGFACTORY->requestBlockRemovalDialog(graphic->getBlockList());

        // list of containers that might refer to the block via inserts:
        QList<PF_Container*> containerList;
        containerList.append(graphic);
        PF_BlockList* blkLst = graphic->getBlockList();
        for (int bi=0; bi<blkLst->count(); bi++) {
            containerList.append(blkLst->at(bi));
        }
        
        if (block!=NULL) {
            
            for (int i = 0; i < containerList.size(); ++i) {
        
                PF_Container* cont = containerList.at(i);
                // remove all inserts from the graphic:
                bool done;
                do {
                    done = true;
                    for (PF_Entity* e=cont->firstEntity(LX_Define::ResolveNone);
                            e!=NULL;
                            e=cont->nextEntity(LX_Define::ResolveNone)) {

                        if (e->rtti()==LX_Define::EntityInsert) {
                            PF_Insert* ins = (PF_Insert*)e;
                            if (ins->getName()==block->getName()) {
                                cont->removeEntity(ins);
                                done = false;
                                break;
                            }
                        }
                    }
                } while (!done);
            }

			// close all windows that are editing this block:
        	if (PF_DIALOGFACTORY!=NULL) {
	            PF_DIALOGFACTORY->closeEditBlockWindow(block);
    	    }

            // Now remove the block from the block list:
            graphic->removeBlock(block);
            graphic->updateInserts();
			graphicView->redraw(LX_Define::RedrawDrawing); 

        }
    }

    finish();
    PF_DIALOGFACTORY->updateSelectionWidget(container->countSelected());
}



void WF_BlocksRemove::init(int status) {
    PF_ActionInterface::init(status);
    trigger();
}

// EOF
